package com.wechat.servlet;

import com.alibaba.fastjson.JSONArray;
import com.wechat.DAO.DaoImpl.MessageDAOIpml;
import com.wechat.DAO.MessageDAO;
import com.wechat.pojo.Message;
import com.wechat.pojo.SenderCallBack;
import com.wechat.servlet.Utils.Base64Decoder;
import com.wechat.servlet.Utils.Base64Encoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SendMsgServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long oldTime = Long.valueOf(request.getParameter("M_Time"));
        long newTime = System.currentTimeMillis();
        String RID = request.getParameter("RID");
        String SID = request.getParameter("SID");
        int M_Type = Integer.valueOf(request.getParameter("M_Type"));
        String base64Content = request.getParameter("M_Content");
        System.out.println(base64Content);
        String M_Content = Base64Decoder.decode(base64Content);
        System.out.println(M_Content);
//        boolean IF_Send = false;    //发送者是否收到新的时间戳
//        boolean IF_Receive = false;    //接收者是否通过轮询获取到消息
        MessageDAO messageDAO = new MessageDAOIpml();
        //图片特殊处理
        if(M_Type == 2){
            Message message = new Message(oldTime,RID,SID,M_Type,M_Content,true,false);
            if(messageDAO.add(message)){
                response.getWriter().write("success");
            }else {
                //失败，告诉客户端去删除该消息
                response.getWriter().write("fail");
            }
            return;
        }
        //其他正常处理
        Message message = new Message(newTime,RID,SID,M_Type,M_Content,false,false);
        if(messageDAO.add(message)){
            Message message1 = messageDAO.query(newTime);

//            SenderCallBack callBack = new SenderCallBack(oldTime,newTime);
            Object obj = JSONArray.toJSON(message1);
            String json = obj.toString();
            System.out.println(json);
            String base64Json = Base64Encoder.encode(json);
            response.getWriter().write(base64Json);
        }else {
            response.getWriter().write("fail");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
